package com.pet.serve.controller;

import com.pet.serve.entity.Customers;
import com.pet.serve.repository.CustomerRepository;
import com.pet.serve.entity.Goods;
import com.pet.serve.entity.Message;
import com.pet.serve.response.ApiResponse;
import com.pet.serve.service.IndexService;
import com.pet.serve.service.GoodsService;
import com.pet.serve.service.MessageService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import java.util.List;

@RestController
@RequestMapping("/api/index")
public class IndexController {

    private final MessageService messageService;
    private final CustomerRepository customerRepository;

    @Autowired
    public IndexController(MessageService messageService, CustomerRepository customerRepository) {
        this.messageService = messageService;
        this.customerRepository = customerRepository;
    }




    /**
     * 获取用户的未读消息
     * @param username 用户名
     * @return 未读消息列表和数量
     */
    @GetMapping("/getunread")
    public ResponseEntity<Map<String, Object>> getUnreadMessages(@RequestParam String username) {
        List<Message> messages = messageService.getUnreadMessages(username);
        int totalUnread = messages.size();
        Map<String, Object> response = new HashMap<>();
        response.put("message", messages);
        response.put("total", totalUnread);
        return ResponseEntity.ok(response);
    }

    /**
     * 标记消息为已读
     * @param refobs 要标记为已读的消息ID对象
     * @return 操作结果
     */
    @PutMapping("/read")
    public ResponseEntity<?> markMessagesAsRead(@RequestBody List<Map<String, Long>> refobs) {
        List<Long> messageIds = new ArrayList<>();
        for (Map<String, Long> ref : refobs) {
            if (ref.containsKey("investid")) {
                messageIds.add(ref.get("investid"));
            } else if (ref.containsKey("careid")) {
                messageIds.add(ref.get("careid"));
            }
        }
        messageService.markMessagesAsRead(messageIds);
        return ResponseEntity.ok().body("Messages marked as read successfully.");
    }

    @GetMapping("/getnum")
    public ResponseEntity<Map<String, Object>> getNums() {
        Map<String, Object> numsData = IndexService.getNums();
        return ResponseEntity.ok(numsData);
    }

    // 今日推荐商品 API
    @GetMapping("/getrecommended")
    public ResponseEntity<Map<String, Object>> getRecommendedGoods() {
        Map<String, Object> response = new HashMap<>();

        // 获取推荐商品
        List<Goods> recommendedGoods = GoodsService.getRecommendedGoods();

        response.put("success", !recommendedGoods.isEmpty());
        response.put("data", recommendedGoods.isEmpty() ? null : recommendedGoods);
        response.put("message", recommendedGoods.isEmpty() ? "No recommended goods available." : "");

        return ResponseEntity.ok(response);
    }


    @GetMapping("/getuseractivity")
    public ApiResponse getUserActivity() {
        // 查询所有用户
        List<Customers> customersList = customerRepository.findAll();

        // 将用户信息转换为需要的格式
        List<UserActivityDTO> userActivities = customersList.stream()
                .map(customer -> new UserActivityDTO(customer.getNickname(), customer.getRegday()))
                .collect(Collectors.toList());

        // 返回结果
        return new ApiResponse(true, "User activities fetched successfully", userActivities);
    }

    // 内部类用于封装需要返回给前端的数据格式
    @Setter
    @Getter
    public static class UserActivityDTO {
        // Getters 和 Setters
        private String nickname;
        private String regday;

        public UserActivityDTO(String nickname, Date regday) {
            this.nickname = nickname;
            this.regday = regday != null ? regday.toString() : "N/A";
        }

    }

}
